package com.clouddms.config;

import com.clouddms.entity.Admin;
import com.clouddms.entity.User;
import com.clouddms.repository.AdminRepository;
import com.clouddms.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 数据初始化器
 * 用于创建默认的管理员和测试用户账户
 */
@Component
public class DataInitializer implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(DataInitializer.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private Environment environment;

    @Override
    public void run(String... args) throws Exception {
        // 初始化管理员账户（所有环境都需要）
        initializeAdminAccounts();
        
        // 只在开发和测试环境初始化测试用户账户
        String[] activeProfiles = environment.getActiveProfiles();
        boolean isProductionEnv = false;
        for (String profile : activeProfiles) {
            if ("prod".equals(profile)) {
                isProductionEnv = true;
                break;
            }
        }
        
        if (!isProductionEnv) {
            logger.info("当前环境非生产环境，创建测试用户账户");
            initializeTestUserAccounts();
        } else {
            logger.info("生产环境模式：跳过测试用户账户创建");
        }
    }

    private void initializeAdminAccounts() {
        // 创建admin管理员账户
        if (!adminRepository.existsByUsername("admin")) {
            Admin admin = new Admin();
            admin.setUsername("admin");
            admin.setPassword(passwordEncoder.encode("admin123"));
            admin.setEmail("admin@clouddms.com");
            
            adminRepository.save(admin);
            logger.info("创建默认管理员账户: admin/admin123");
        }

        // 创建system管理员账户
        if (!adminRepository.existsByUsername("system")) {
            Admin system = new Admin();
            system.setUsername("system");
            system.setPassword(passwordEncoder.encode("system123"));
            system.setEmail("system@clouddms.com");
            
            adminRepository.save(system);
            logger.info("创建系统管理员账户: system/system123");
        }
    }

    private void initializeTestUserAccounts() {
        // 测试用户配置
        String[][] testUsers = {
            {"testuser", "testuser123", "test@clouddms.com"},
            {"demo", "demo123", "demo@clouddms.com"},
            {"alice", "alice123", "alice@clouddms.com"},
            {"bob", "bob123", "bob@clouddms.com"}
        };

        for (String[] userData : testUsers) {
            String username = userData[0];
            String password = userData[1];
            String email = userData[2];

            if (!userRepository.existsByUsername(username)) {
                User user = new User();
                user.setUsername(username);
                user.setPassword(passwordEncoder.encode(password));
                user.setEmail(email);
                user.setIsActive(true);
                
                // 设置默认角色
                Set<User.UserRole> roles = new HashSet<>();
                roles.add(User.UserRole.USER);
                user.setRoles(roles);
                
                userRepository.save(user);
                logger.info("创建测试用户账户: {}/{}", username, password);
            }
        }
    }
}